package top.lanscarlos.ashcraft.controller;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.util.UUID;

/**
 * Ashcraft
 * top.lanscarlos.ashcraft.controller
 *
 * @author Lanscarlos
 * @since 2022-05-25 14:15
 */
public abstract class AshController {

    @Autowired
    ApplicationContext context;

    @Autowired
    Gson gson;

    @Nullable
    public String handleMultipartFile(ServletContext context, MultipartFile file) {
        if (file == null) return null;
        try {
            String path = context.getRealPath("/images/");
            String name = UUID.randomUUID().toString().replace("-", "");
            System.out.println(path);
            File target = new File(path + name + ".png");
            if (!target.getParentFile().exists()) {
                target.getParentFile().mkdirs();
            }
            file.transferTo(target);
            return name;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public JsonElement toJsonTree(Object object) {
        return gson.toJsonTree(object);
    }

    public JsonElement toJson(Object object) {
        return toJsonTree(object);
    }

    public <T> JsonElement asJson(String name, Class<T> tClass) {
        return toJsonTree(getBean(name, tClass));
    }

    public <T> JsonElement asJson(Class<T> tClass) {
        return toJsonTree(getBean(tClass));
    }

    public JsonElement asJson(String name) {
        return toJsonTree(getBean(name));
    }

    public <T> T getBean(String name, Class<T> tClass) {
        return context.getBean(name, tClass);
    }

    public <T> T getBean(Class<T> tClass) {
        return context.getBean(tClass);
    }

    public Object getBean(String name) {
        return context.getBean(name);
    }
}
